import unittest
import requests
import random
from bs4 import BeautifulSoup

from api.login import LoginAPI
from api.top_up import Top_up_api


class Test_tup_up(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        cls.session = requests.session()
        cls.Top_up_api = Top_up_api()
        cls.LoginAPI = LoginAPI()
        resp = cls.LoginAPI.login666(cls.session, {"keywords": "13611160006", "password": "a123123"})
        print(resp.json())

    @classmethod
    def tearDownClass(cls) -> None:
        cls.session.close()

    # 获取充值验证码
    def test01_get_verifycode(self):
        resp = self.Top_up_api.get_verifycode(session=self.session, r=random.random())
        print(resp.text)
        with open('../image/verify.png' ,'wb')as f:
            f.write(resp.content)

    # 充值
    def test02_tup_up(self):
        data_dict = {
            "paymentType":"chinapnrTrust",
            "amount":"100",
            "formStr":"reForm",
            "valicode":"8888"
        }
        resp = self.Top_up_api.tup_up(session=self.session, data_dict=data_dict)
        print(resp.json())

        # 第三方充值
        #提取第三方URL
        html = resp.json().get('description').get('form')
        # 解析hmtl数据
        suop = BeautifulSoup(html, "html.parser")
        # 提取url9
        html_url = suop.form.get('action')
        # 提取请求方法
        html_method = suop.form.get('method')

        # 提取请求参数
        resp_data = {}
        for i in suop.find_all('input'):
            value = i.get('value')
            name = i.get('name')
            # name_data = "name"
            resp_data[name] = value
        print("第三方请求参数：",resp_data)

        # 进行第三方充值请求
        resp_3 = requests.post(url=html_url, data=resp_data)
        print(resp_3.text)



if __name__ == '__main__':
    unittest.main()